package io.coderyeah.ymcc.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import io.coderyeah.ymcc.constant.YmccConstants;
import io.coderyeah.ymcc.enums.YmccSystemError;
import io.coderyeah.ymcc.exception.BusinessException;
import io.coderyeah.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lqs
 * @date 2022/10/20 11:12
 */
@Service
@Slf4j
public class VerifyCodeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public JSONResult sendSmsCode(String phone) {
        if (!Validator.isMobile(phone)) {// 判断手机号是否合法
            throw new BusinessException(YmccSystemError.PHONE_PARAM_ERROR);
        }
        // 用于存放验证码
        String code = "";
        // 查询手机号验证码是否已经存在未过期
        final String value = stringRedisTemplate.opsForValue().get(YmccConstants.REGISTER_CODE + phone);
        if (value != null) {// 没有过期
            // 获取时间 判断是否频繁操作
            long oldTime = Long.parseLong(value.split(":")[1]);
            if (System.currentTimeMillis() - oldTime <= 1000 * 60) {
                // 一分钟之内不允许频繁操作
                throw new BusinessException(YmccSystemError.FREQUENT_OPERATION);
            } else {
                code = value.split(":")[0];
            }
        } else {
            // 验证码过期 生成新的验证码
            code = RandomUtil.randomNumbers(6);
        }
        // 存入redis
        stringRedisTemplate.opsForValue().set(YmccConstants.REGISTER_CODE + phone, code + ":" + System.currentTimeMillis(), 10L, TimeUnit.MINUTES);
        // 发送验证码短信
//        SmsUtils.sendSms(phone, "您的验证码是：" + code + ",请在十分钟之内使用。");
        log.info("=========您的验证码是:{}=========", code);
        return JSONResult.success();
    }
}
